import { createRouter, createWebHashHistory } from 'vue-router';

import dbRouters from "@/views/db/router";
import cs4plRouters from '@/views/cs4pl/router';
import hwcloudRouters from '@/views/hwcloud/router';
import capitalandRouters from '@/views/capitaland/router';
import toolsRouters from '@/views/tools/router';
import devopsRouters from '@/views/devops/router';
import shareRouters from '@/views/shares/router';
import rbacRouters from '@/views/rbac/router';

const routes = [
  {
    path: '/login',
    name: 'LogIn',
    meta: { title: '登录' },
    component: () => import('@/views/LogIn.vue')
  },
  {
    path: '/',
    component: () => import('@/views/shared/Workbench.vue'),
    children: [
      {
        path: "/",
        meta: {
          title: "工作台",
          activeMenu: 0
        },
        name: "Index",
        component: () => import("@/views/Home.vue")
      },
      ...dbRouters,
      ...cs4plRouters,
      ...hwcloudRouters,
      ...capitalandRouters,
      ...toolsRouters,
      ...shareRouters,
      ...devopsRouters,
      ...rbacRouters,
      {
        path: '/docs',
        name: "ApiDocuments",
        meta: {
          title: "Api文档",
          activeMenu: 1
        },
        component: () => import("@/views/shared/ApiDocument.vue")
      },
      {
        path: '/about',
        name: 'About',
        meta: { title: '关于' },
        component: () => import('@/views/shared/About.vue')
      }
    ]
  },
  {
    path: '/:catchAll(.*)*',
    name: 'notfound',
    component: () => import('@/views/shared/Workbench.vue'),
    children: [{
      path: '',
      name: '404',
      component: () => import('@/views/shared/404.vue')
    }]
  }
];

const router = createRouter({
  history: createWebHashHistory('/'),
  routes
});

let app = null;
let proxy = new Proxy(router.install, {
  apply: function (target, ctx, args) {
    app = args[0];

    Reflect.apply(...arguments);
  }
});

router.install = proxy;

router.beforeEach((to, from, next) => {
  let store = app._context.provides.store;
  let token = store.state.oauth;

  if (sessionStorage.getItem('auth')) {
    try {
      let auth = JSON.parse(sessionStorage.getItem('auth'));

      store.commit('fillConfigs', auth);
    } catch { }
  }

  if (to.path == '/login') {
    next();

    return;
  }

  if (window.settings.needLogIn == true && !store.state.user.authenticated) {
    router.push('/login');

    return;
  }

  if (store.enable && !token.access_token) {
    app.$http.post('/AuthCenter/api/oauth/token', window.settings.oauth).then(res => {
      store.commit('authcate', res);

      next();
    });
  } else if (store.enable && store.getters.tokenIsExpires()) {
    refreshToken().then(res => {
      store.commit('authcate', res);

      next();
    });
  } else {
    next();
  }
});

router.afterEach((to, from) => {
  document.title = `${window.settings.title} | ${to.meta.title || ''}`;
});

let refreshToken = async () => {
  let store = $app._context.provides.store;
  let res = await $app.$http.get(`/AuthCenter/api/oauth/token/refresh/${store.state.oauth.access_token}`);

  return res;
};

export default router;